package com.ant.storage.service.impl;

import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.SalesDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.SalesMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.IInventoryLogService;
import com.ant.storage.service.IInventoryService;
import com.ant.storage.service.ISalesDetailsService;
import com.ant.storage.service.ISalesService;
import com.ant.storage.utils.RandomUtil;
import com.ant.storage.vo.SalesCommodityVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletContext;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2022-11-03
 */
@Service
public class SalesServiceImpl extends ServiceImpl<SalesMapper, Sales> implements ISalesService {

    @Autowired
    ISalesDetailsService salesDetailsService;

    @Autowired
    ISalesService salesService;

    @Autowired
    IInventoryService inventoryService;

    @Autowired
    IInventoryLogService inventoryLogService;
    @Autowired
    public ServletContext servletContext;

    @Override
    public PageInfo<Sales> querylist(SalesDto dto) {
        try {
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<Sales> wrapper = new QueryWrapper<>();
            if (dto.getWarehouseId() != null) {
                wrapper.in("warehouse_id", dto.getWarehouseId());
            }
            if (StringUtils.isNotEmpty(dto.getOddNumbers())) {
                wrapper.like("odd_numbers", dto.getOddNumbers());
            }
            if (StringUtils.isNotEmpty(dto.getBeginTimes())) {
                wrapper.ge("creation_time", dto.getBeginTimes() + " 00:00:00");
            }
            if (StringUtils.isNotEmpty(dto.getEndTimes())) {
                wrapper.le("creation_time", dto.getEndTimes() +" 23:59:59");
            }
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            wrapper.eq("city_id",userInfo.getCityId());

            wrapper.eq("is_delete",1);
            wrapper.orderByDesc("id");
            List<Sales> salesList = this.baseMapper.selectList(wrapper);
            salesList.stream().map(item -> {
                //查詢商品
                List<SalesCommodityVo> list = this.baseMapper.findByIdList(item.getId());
                item.setDetailsList(list);
                return item;
            }).collect(Collectors.toList());

            PageInfo<Sales> pageInfo = new PageInfo<>(salesList);
            return pageInfo;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo saveSales(Sales sales) {
        try {
            sales.setOddNumbers(RandomUtil.getOrderNumbers(this.baseMapper.selectLastID()));
            sales.setCreationTime(new Date());
            sales.setCreationBy(sales.getCreationBy());
            if (sales.getId() == null) {
                this.baseMapper.insert(sales);
            }
            if (sales.getDetailsList().size() > 0) {
                List<SalesDetails> collect = sales.getDetailsList().stream().map(item -> {
                    SalesDetails details = new SalesDetails();
                    details.setId(item.getId());
                    details.setInventoryId(item.getInventoryId());
                    details.setSalesId(sales.getId());
                    details.setActualQuantity(item.getActualQuantity());
                    Inventory serviceOne = inventoryService.getOne(new QueryWrapper<Inventory>().eq("id",
                            item.getInventoryId()));
                    if (serviceOne != null) {
                        BigDecimal GoodsAmount = serviceOne.getGoodsAmount()
                                .add(new BigDecimal(item.getActualQuantity()));
                        GoodsAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
                        inventoryService.update(new UpdateWrapper<Inventory>()
                                .set("goods_amount",GoodsAmount)
                                .eq("id", item.getInventoryId()));
                    }
                    InventoryLog log = new InventoryLog();
                    log.setWarehouseId(sales.getWarehouseId());
                    log.setInventoryId(item.getInventoryId());
                    log.setGoodsAmount("-"+item.getActualQuantity());
                    log.setStockState(2);
                    log.setGoodsPrice(serviceOne.getGoodsPrice());
                    log.setCreatorBy(sales.getCreationBy());
                    log.setCreationTime(new Date());
                    log.setRemark("退货入库");
                    inventoryLogService.save(log);
                    return details;
                }).collect(Collectors.toList());
                salesDetailsService.saveBatch(collect);
                return ResultVo.success("提交成功");
            } else {
                throw new AntException(ResultCode.PARAM_IS_BLANK);
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
            return ResultVo.fail(e.getMessage());
        }

    }

    @Override
    public Sales getSalesByID(Integer id) {
        Sales selectOne = this.baseMapper.selectOne(new QueryWrapper<Sales>().eq("id", id));
        if (selectOne == null) {
            throw new AntException(ResultCode.NOT_FOUND);
        }
        //查詢商品
        List<SalesCommodityVo> list = this.baseMapper.findByIdList(selectOne.getId());
        selectOne.setDetailsList(list);
        return selectOne;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo  updates(Integer id) {
        List<SalesDetails> list = salesDetailsService.list(new QueryWrapper<SalesDetails>()
                .eq("sales_id", id));
        if (list == null && list.size()==0) {
            return ResultVo.fail("没有物品信息");
        }
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        list.stream().forEach(item->{
            Inventory one = inventoryService.getOne(new QueryWrapper<Inventory>().eq("id", item.getInventoryId()));
            if(one==null){
                throw new AntException(ResultCode.NOT_FOUND);
            }
            BigDecimal GoodsAmount = one.getGoodsAmount()
                    .add(new BigDecimal(item.getActualQuantity()));
            GoodsAmount.setScale(2, BigDecimal.ROUND_HALF_UP);

            Inventory inventory=new Inventory();
           inventory.setId(item.getInventoryId());
           inventory.setGoodsAmount(GoodsAmount);
           inventoryService.updateById(inventory);
            InventoryLog log = new InventoryLog();
            log.setWarehouseId(one.getWarehouseId());
            log.setInventoryId(one.getId());
            log.setPurchaserId(null);
            log.setGoodsAmount(item.getActualQuantity()); // 入库实际数量
            log.setGoodsPrice(one.getGoodsPrice()); // 入库实际数量
            log.setStockState(1); // 入库
            log.setRemark("部门退货入库"); // 入库
            log.setSubscribeId(id); // 采购单id
            log.setPurchaseOrdersId(null);
            log.setCreatorBy(userInfo.getNameId().toString());
            log.setCreationTime(new Date());
            inventoryLogService.save(log);
        });
        salesService.update(new UpdateWrapper<Sales>().set("is_delete", 0).eq("id", id));
        return ResultVo.success("操作成功");
    }
}
